<template>
  <div class='app-container'>
    <div class='button-container'>
      <el-button class='filter-item' type='primary' @click='openCreateUserDialog' icon='edit'>新增用户</el-button>
    </div>
    <div>

      <!-- 表格 -->
      <el-table ref="userTable" @selection-change="onSelectionChanged" :data="GridPageList"
                v-loading.body="gridDataIsLoading"
                element-loading-text="数据加载中..." border fit highlight-current-row>

        <el-table-column align="center" label='序号' width="150">
          <template scope="scope">
            {{scope.$index + 1}}
          </template>
        </el-table-column>

        <el-table-column label="用户名" width="200">
          <template scope="scope">
            {{scope.row.username}}
          </template>
        </el-table-column>

        <el-table-column label="昵称" width="200">
          <template scope="scope">
            {{scope.row.usernickname}}
          </template>
        </el-table-column>

        <el-table-column label="手机号" width="250">
          <template scope="scope">
            {{scope.row.userphoneno > 0 ? scope.row.userphoneno : '未设置'}}
          </template>
        </el-table-column>

        <el-table-column label="岗位" width="450">
          <template scope="scope">
            <template v-for="role in scope.row.userroles">
              <el-tag
                type='primary' close-transition>{{role.rolename}}
              </el-tag>
            </template>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作">
          <template scope="scope">
            <el-button icon="edit" size="small" @click='openSetUserRoleDialog(scope.$index,scope.row)'>设置岗位</el-button>
            <el-button icon="delete" type="danger" size="small" @click="deleteUser(scope.$index, scope.row)">删除用户
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页 -->
    <div v-show="!gridDataIsLoading" class="pagination-container">
      <el-pagination @size-change="onPageSizeChanged" @current-change="onPageNoChanged"
                     :current-page.sync="paginationConfig.currentQueryPage"
                     :page-sizes="[10,20,30, 50]" :page-size="paginationConfig.selectedPageSize"
                     layout="total, sizes, prev, pager, next, jumper" :total="dataCount">
      </el-pagination>
    </div>
    <!-- 新增员工 -->
    <el-dialog title='初始化用户' :visible.sync='createUserDialogOpend' @close='closeUserForm'>
      <el-form :model="newuser" ref="userForm" :rules="rules">
        <el-form-item label='登录邮箱' prop="username">
          <el-input v-model='newuser.username' placeholder="请输入用户登录邮箱"></el-input>
        </el-form-item>
      </el-form>
      <div slot='footer' class='dialog-footer'>
        <el-button type='primary' @click='handleCreateUserSubmit'>确定</el-button>
        <el-button @click='createUserDialogOpend = false'>取消</el-button>
      </div>
    </el-dialog>

    <!-- 指定岗位 -->
    <el-dialog title='指定岗位' :visible.sync='setUserRoleDialogOpend' size="tiny">
      <div class="role-transfer">
        <el-transfer v-model="selectdRoles"
                     :titles="['未选岗位', '已选岗位']"
                     :props="{ key: 'roleid', label: 'rolename'}"
                     :data="allRoles"></el-transfer>
      </div>
      <div slot='footer' class='dialog-footer'>
        <el-button type='primary' @click='handleSetUserRoleSubmit'>确定</el-button>
        <el-button @click='setUserRoleDialogOpend = false'>取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {isEmail} from '@/utils/validate';

  export default {
    name: 'userset',
    data() {
      // 校验邮箱
      const validateEmail = (rule, value, callback) => {
        if (!isEmail(value)) {
          callback(new Error('请输入正确的合法邮箱'));
        } else {
          callback();
        }
      };
      // 校验用户名是否存在
      const validateUserExists = (rule, value, callback) => {
        console.log(value);
        this.$http.get('/Oss/Auth/CheckUserExsists', {
          params: {
            username: value
          }
        }).then((response) => {
          if (response.data.isSuccess) {
            let userexists = response.data.userexists;
            if (userexists) {
              callback(new Error('用户名已存在'));
            } else {
              callback();
            }
          } else {
            callback(new Error('用户服务不可用,请稍后再试'));
          }
        });
      };
      return {
        gridDataSource: [],
        selectdRoles: [],
        currentSelectedRow: null,
        // 当前分页数据开始index
        startIndex: 0,
        // 当前分页数据结束index
        endIndex: 0,
        gridDataIsLoading: false,
        paginationConfig: {selectedPageSize: 10, currentQueryPage: 0},
        createUserDialogOpend: false,
        setUserRoleDialogOpend: false,
        newuser: {
          username: ''
        },
        allRoles: [],
        rules: {
          username: [
            {required: true, trigger: 'blur', message: '用户名必填'},
            {type: 'string', max: 50, trigger: 'blur', message: '用户名必须小于50个字'},
            {validator: validateEmail, trigger: 'blur'},
            {validator: validateUserExists, trigger: 'blur'}
          ]
        }
      };
    },
    methods: {
      /**
       * 刷新数据
       */
      refreshData() {
        this.gridDataIsLoading = true;

        let getRoles = this.$http.get('/Oss/Auth/GetAllRoles').then((response) => {
          if (response.data.isSuccess) {
            this.allRoles = response.data.roles;
          }
        });

        let getUsers = this.$http.get('/Oss/Auth/GetAllUsers').then((response) => {
          if (response.data.isSuccess) {
            this.gridDataSource = response.data.userlist;
            this.paginationConfig.currentQueryPage = 1;
          }
          this.paginationConfig.currentQueryPage = 0;
        });

        this.$http.all([getRoles, getUsers]).then(() => {
          this.gridDataIsLoading = false;
        }).catch(() => {
          this.gridDataIsLoading = false;
        });
      },
      computeDataIndex(pageNo, pageSize) {
        this.startIndex = pageSize * (pageNo - 1) + 1;
        this.endIndex = this.startIndex + pageSize;
        console.log(this.startIndex);
        console.log(this.endIndex);
      },
      /**
       * 分页变化
       */
      onPageSizeChanged(size) {
        this.paginationConfig.selectedPageSize = size;
        this.computeDataIndex(this.paginationConfig.currentQueryPage, size);
      },
      onPageNoChanged(page) {
        this.paginationConfig.currentQueryPage = page;
        this.computeDataIndex(page, this.paginationConfig.selectedPageSize);
      },
      /**
       * 表格selectchanged
       */
      onSelectionChanged(select) {
        this.currentSelectedRow = select;
      },
      closeUserForm() {
        this.$refs['userForm'].resetFields();
        this.newuser = {
          username: ''
        };
      },
      openCreateUserDialog() {
        this.createUserDialogOpend = true;
      },
      /**
       * 绑定用户岗位
       */
      handleSetUserRoleSubmit() {
        let userid = this.currentSelectedRow.userid;
        this.$http.post('/Oss/Auth/SaveUserRoles', {
          userid: userid,
          roleids: this.selectdRoles
        }).then((response) => {
          if (response.data.isSuccess) {
            this.$message({
              message: '指定岗位成功!',
              type: 'success'
            });
            this.setUserRoleDialogOpend = false;
          }
        }).then(() => {
          this.$http.get('/Oss/Auth/GetUserInfo', {
            params: {
              userid: userid
            }
          }).then((response) => {
            if (response.data.isSuccess) {
              let updateIndex = this.gridDataSource.findIndex((user) => {
                return user.userid === userid;
              });
              console.log(updateIndex);
              this.gridDataSource.splice(updateIndex, 1, response.data.user);
            }
          });
        }).catch(() => {
          this.$message({
            message: '数据保存失败!',
            type: 'error'
          });
        });
      },
      /**
       * 提交新增用户表单
       */
      handleCreateUserSubmit() {
        this.$refs.userForm.validate((valid) => {
          if (valid) {
            this.$http.post('/Oss/Auth/InitUser', {username: this.newuser.username}).then((response) => {
              if (response.data.isSuccess) {
                this.$message({
                  message: '新增成功!',
                  type: 'success'
                });
                if (response.data.user) {
                  this.gridDataSource.push(response.data.user);
                }
                this.newuser = {
                  username: ''
                };
                this.createUserDialogOpend = false;
              } else {
                this.$message({
                  message: '数据提交出现错误,请稍后重试!',
                  type: 'error'
                });
              }
            }).catch(() => {
              this.$message({
                message: '数据提交出现错误,请稍后重试!',
                type: 'error'
              });
            });
          } else {
            return false;
          }
        });
      },
      /**
       * 删除用户
       */
      deleteUser(index, row) {
        let userid = row.userid;
        if (userid && userid > 0) {
          this.$confirm('删除用户后该用户将不能登录到本系统, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
              this.$http.delete('/Oss/Auth/DeleteUser', {
                params: {
                  userid: userid
                }
              }).then((response) => {
                if (response.data.isSuccess) {
                  console.log(index);
                  console.log(row.userid);
                  this.gridDataSource.splice(index, 1);
                  this.$message({
                    message: '删除成功!',
                    type: 'success'
                  });
                }
              });
            }
          );
        }
      },
      openSetUserRoleDialog(index, row) {
        this.currentSelectedRow = row;
        /**
         * 初始化已选择
         */
        this.selectdRoles.splice(0, this.selectdRoles.length);
        if (row.userroles) {
          row.userroles.forEach(x => {
            this.selectdRoles.push(x.roleid);
          });
        }
        this.setUserRoleDialogOpend = true;
      }
    },
    created() {
      this.refreshData();
    },
    computed: {
      GridPageList() {
        if (this.gridDataSource && this.gridDataSource.length > 0) {
          if (this.startIndex > 0 && this.endIndex > 0) {
            return this.gridDataSource.slice(this.startIndex - 1, this.endIndex - 1);
          } else {
            return [];
          }
        } else {
          return [];
        }
      },
      dataCount() {
        if (this.gridDataSource) {
          return this.gridDataSource.length;
        } else {
          return 0;
        }
      }
    }
  };
</script>

<style rel="stylesheet/scss" lang="scss">
  .role-transfer {
    display: inline-flex;
    position: relative;
    justify-content: center;
    align-items: center;
    width: 100%;

  }
</style>
